from langgraph.graph import StateGraph, START, END
from pydantic import BaseModel

# 定义图的整体状态
class OverallState(BaseModel):
    a: str

def node(state: OverallState):
    return {"a": "goodbye"}

# 构建状态图
builder = StateGraph(OverallState)
builder.add_node(node)  # 添加第一个节点
builder.add_edge(START, "node")  # 从节点开始
builder.add_edge("node", END)  # 结束节点
graph = builder.compile()

# 测试有效输入
# graph.invoke({"a": "hello"})


try:
    graph.invoke({"a": 123})  # 这里应该是一个字符串
except Exception as e:
    print("\n因为 `a` 是整数而不是字符串，抛出了异常。")
    print(e)


def bad_node(state: OverallState):
    return {
        "a": 123  # 无效，应该是字符串
    }

def ok_node(state: OverallState):
    return {"a": "goodbye"}

# 构建状态图
builder = StateGraph(OverallState)
builder.add_node(bad_node)
builder.add_node(ok_node)
builder.add_edge(START, "bad_node")
builder.add_edge("bad_node", "ok_node")
builder.add_edge("ok_node", END)
graph = builder.compile()

# 测试有效输入
try:
    graph.invoke({"a": "hello"})
except Exception as e:
    print("\n因为 bad_node 将 `a` 设置为整数，抛出了异常。")
    print(e)